package com.zbkj.crmeb.task.order.usercommission;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zbkj.crmeb.enums.OrderStatusEnum;
import com.zbkj.crmeb.store.model.ChannelGroupBooking;
import com.zbkj.crmeb.store.model.StoreOrder;
import com.zbkj.crmeb.store.model.StoreOrderInfo;
import com.zbkj.crmeb.store.model.UserCommission;
import com.zbkj.crmeb.store.response.StoreCartResponse;
import com.zbkj.crmeb.store.response.StoreProductCartProductInfoResponse;
import com.zbkj.crmeb.store.service.ChannelGroupBookingService;
import com.zbkj.crmeb.store.service.StoreOrderInfoService;
import com.zbkj.crmeb.store.service.StoreOrderService;
import com.zbkj.crmeb.store.service.UserCommissionService;
import com.zbkj.crmeb.user.model.User;
import com.zbkj.crmeb.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

@Component
@Configuration
@Slf4j
public class OrderAccountCheckV2Task implements ApplicationRunner {
    @Resource
    private StoreOrderService storeOrderService;
    @Resource
    private UserService userService;
    @Resource
    private UserCommissionService userCommissionService;
    @Resource
    private StoreOrderInfoService storeOrderInfoService;
    @Resource
    private ChannelGroupBookingService channelGroupBookingService;
//    @Resource
//    private
    @Override
    public void run(ApplicationArguments args) throws Exception {

        List<String> list = Arrays.asList("6442", "6447", "6449", "6452", "6458", "6513", "6514", "6524", "6664", "6708", "6723", "6742", "6748", "6778", "6802", "6826", "6905", "6908", "6912", "7039", "7053", "7054", "7056", "7061", "7225", "7334", "7567", "7788", "7854");
        for (String s : list) {
            createUserCommissionExcelUrl(Integer.valueOf(s));
        }


    }

    public String createUserCommissionExcelUrl(Integer uid) throws Exception {

        List<UserCommission> userCommissionList = userCommissionService.list(Wrappers.<UserCommission>lambdaQuery()
                .eq(UserCommission::getUid, uid).eq(UserCommission::getTitle, "购买商品-一级佣金"));


        List<String> subOrderIds = new ArrayList<>();
        Map<String, UserCommission> userCommissionSubOrderIdMap = new HashMap<>();
        for (UserCommission userCommission : userCommissionList) {
            subOrderIds.add(userCommission.getOrderId());
            userCommissionSubOrderIdMap.put(userCommission.getOrderId(), userCommission);
        }
        if (CollectionUtils.isEmpty(subOrderIds)){
            return null;
        }
        List<StoreOrderInfo> storeOrderInfos = storeOrderInfoService.list(Wrappers.<StoreOrderInfo>lambdaQuery().in(StoreOrderInfo::getChildOrderNumber, subOrderIds));

        List<Integer> orderIds = new ArrayList<>();
        Map<Integer, List<StoreOrderInfo>> storeOrderInfoOrderIdMap = new HashMap<>();
        for (StoreOrderInfo storeOrderInfo : storeOrderInfos) {
            if (!orderIds.contains(storeOrderInfo.getOrderId())){
                orderIds.add(storeOrderInfo.getOrderId());
            }
            storeOrderInfoOrderIdMap.computeIfAbsent( storeOrderInfo.getOrderId(), (k) -> new ArrayList<>()).add(storeOrderInfo);
        }
        List<StoreOrder> storeOrders = storeOrderService.list(Wrappers.<StoreOrder>lambdaQuery().in(StoreOrder::getId, orderIds));

        // 解冻佣金map
        List<UserCommission> userCommissionUnFreezeList = userCommissionService.list(Wrappers.<UserCommission>lambdaQuery()
                .eq(UserCommission::getUid, uid).eq(UserCommission::getTitle, "购买商品-一级佣金-解冻"));
        Map<String, UserCommission> userCommissionUnFreezeSubOrderIdMap = new HashMap<>();
        for (UserCommission userCommission : userCommissionUnFreezeList) {
            userCommissionUnFreezeSubOrderIdMap.put(userCommission.getOrderId(), userCommission);
        }

        List<CommissionExcelData> commissionExcelDataList = new ArrayList<>();
        for (StoreOrder storeOrder : storeOrders) {
            CommissionExcelData commissionExcelData = new CommissionExcelData();
            commissionExcelDataList.add(commissionExcelData);

            commissionExcelData.setMainOrderNo(storeOrder.getOrderId());
            commissionExcelData.setTotalPrice(storeOrder.getPayPrice().doubleValue());
            commissionExcelData.setIdCard(maskIdCard(storeOrder.getIdCard()));
            commissionExcelData.setIdCardName(StringUtils.defaultString(storeOrder.getPayName(),storeOrder.getRealName()));
            commissionExcelData.setOrderStatus(OrderStatusEnum.getMsgByCode(storeOrder.getStatus()));
            commissionExcelData.setCreateTime(storeOrder.getCreateTime().toString());

            List<CommissionExcelData.SubCommissionExcelData> subCommissionExcelDataList = new ArrayList<>();
            commissionExcelData.setSubCommissionList(subCommissionExcelDataList);
            List<StoreOrderInfo> storeOrderInfoList = storeOrderInfoOrderIdMap.get(storeOrder.getId());
            for (StoreOrderInfo storeOrderInfo : storeOrderInfoList) {
                CommissionExcelData.SubCommissionExcelData subCommissionExcelData = new CommissionExcelData.SubCommissionExcelData();
                subCommissionExcelDataList.add(subCommissionExcelData);
                subCommissionExcelData.setSubOrderNo(storeOrderInfo.getChildOrderNumber());
                subCommissionExcelData.setSubPrice(storeOrderInfo.getPayPrice().doubleValue());
                subCommissionExcelData.setSubOrderStatus(OrderStatusEnum.getMsgByCode(storeOrderInfo.getStatus()));
                UserCommission userCommission = userCommissionSubOrderIdMap.get(storeOrderInfo.getChildOrderNumber());
                if (null!=userCommission){
                    subCommissionExcelData.setLeaderName(userService.getById(userCommission.getUid()).getNickname());
                    if (null != userCommission.getFreezeAmount()){
                        subCommissionExcelData.setFreezePrice(userCommission.getFreezeAmount().doubleValue());
                    }
                    if (null != userCommission.getWithdrawalAmount()){
                        subCommissionExcelData.setWithdrawPrice(userCommission.getWithdrawalAmount().doubleValue());
                    }
                    if (userCommissionUnFreezeSubOrderIdMap.containsKey(userCommission.getOrderId())){
                        UserCommission userCommissionUnFreeze = userCommissionUnFreezeSubOrderIdMap.get(userCommission.getOrderId());
                        if (null != userCommissionUnFreeze.getFreezeAmount()){
                            subCommissionExcelData.setFreezePrice(userCommissionUnFreeze.getFreezeAmount().doubleValue());
                        }
                        if (null != userCommissionUnFreeze.getWithdrawalAmount()){
                            subCommissionExcelData.setWithdrawPrice(userCommissionUnFreeze.getWithdrawalAmount().doubleValue());
                        }
                    }
                    if (null != userCommission.getActivityGroupId()){
                        ChannelGroupBooking channelGroupBooking = channelGroupBookingService.getOne(Wrappers.<ChannelGroupBooking>lambdaQuery().eq(ChannelGroupBooking::getId, userCommission.getActivityGroupId()));
                        if (null != channelGroupBooking){
                            subCommissionExcelData.setGroupName(channelGroupBooking.getActivityName());
                            subCommissionExcelData.setGroupRate(channelGroupBooking.getRebateRate()+"");
                        }
                    }
                }
                StoreCartResponse storeCartResponse = JSON.parseObject(storeOrderInfo.getInfo(), StoreCartResponse.class);
                if (null != storeCartResponse && null != storeCartResponse.getProductInfo()){
                    StoreProductCartProductInfoResponse productInfo = storeCartResponse.getProductInfo();
                    subCommissionExcelData.setProductName(productInfo.getStoreName());
                    if (null != productInfo.getAttrInfo()){
                        subCommissionExcelData.setProductAttr(productInfo.getAttrInfo().getSuk());
                    }
                }


            }
        }
        User user = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getUid, uid));
        createExcel(commissionExcelDataList,StringUtils.defaultIfBlank(user.getRealName(),user.getNickname()));
        return "";

    }
    public void createExcel(List<CommissionExcelData> commissionDataList,String excelName) throws Exception {
        // 创建工作簿和工作表
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("佣金表");

        // 创建标题行
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("主订单号");
        headerRow.createCell(1).setCellValue("支付总金额");
        headerRow.createCell(2).setCellValue("身份证号");
        headerRow.createCell(3).setCellValue("身份证名字");
        headerRow.createCell(4).setCellValue("订单状态");
        headerRow.createCell(5).setCellValue("订单创建时间");

        headerRow.createCell(6).setCellValue("子订单号");
        headerRow.createCell(7).setCellValue("子订单支付金额");
        headerRow.createCell(8).setCellValue("子订单状态");
        headerRow.createCell(9).setCellValue("分销员名字");
        headerRow.createCell(10).setCellValue("冻结金额");
        headerRow.createCell(11).setCellValue("可提现金额");
        headerRow.createCell(12).setCellValue("团购名称");
        headerRow.createCell(13).setCellValue("团购佣金比例");
        headerRow.createCell(14).setCellValue("商品名称");
        headerRow.createCell(15).setCellValue("商品规格");


        // 填充数据
        int rowIndex = 1;
        String currentMainOrder = null;
        int startRow = 0;

        for (CommissionExcelData commissionData : commissionDataList) {
            if (!commissionData.getMainOrderNo().equals(currentMainOrder)) {
                if (currentMainOrder != null) {
                    // 合并单元格
                    CellRangeAddress cellRange = new CellRangeAddress(startRow, rowIndex - 1, 0, 0);
                    sheet.addMergedRegion(cellRange);
                    cellRange = new CellRangeAddress(startRow, rowIndex - 1, 1, 1);
                    sheet.addMergedRegion(cellRange);
                }
                currentMainOrder = commissionData.getMainOrderNo();
                startRow = rowIndex;
            }

            for (CommissionExcelData.SubCommissionExcelData subCommission : commissionData.getSubCommissionList()) {
                Row dataRow = sheet.createRow(rowIndex);
                dataRow.createCell(0).setCellValue(commissionData.getMainOrderNo());
                dataRow.createCell(1).setCellValue(commissionData.getTotalPrice());
                dataRow.createCell(2).setCellValue(commissionData.getIdCard());
                dataRow.createCell(3).setCellValue(commissionData.getIdCardName());
                dataRow.createCell(4).setCellValue(commissionData.getOrderStatus());
                dataRow.createCell(5).setCellValue(commissionData.getCreateTime());
                dataRow.createCell(6).setCellValue(subCommission.getSubOrderNo());
                dataRow.createCell(7).setCellValue(subCommission.getSubPrice());
                dataRow.createCell(8).setCellValue(subCommission.getSubOrderStatus());
                dataRow.createCell(9).setCellValue(StringUtils.defaultString(subCommission.getLeaderName(),""));
                dataRow.createCell(10).setCellValue(null==subCommission.getFreezePrice()?0:subCommission.getFreezePrice());
                dataRow.createCell(11).setCellValue(null == subCommission.getWithdrawPrice() ? 0 : subCommission.getWithdrawPrice());
                dataRow.createCell(12).setCellValue(StringUtils.defaultString(subCommission.getGroupName(),""));
                dataRow.createCell(13).setCellValue(StringUtils.defaultString(subCommission.getGroupRate(),""));
                dataRow.createCell(14).setCellValue(subCommission.getProductName());
                dataRow.createCell(15).setCellValue(subCommission.getProductAttr());

                rowIndex++;
            }
        }

        // 处理最后一个主订单的合并
        if (currentMainOrder != null) {
            CellRangeAddress cellRange = new CellRangeAddress(startRow, rowIndex - 1, 0, 0);
            sheet.addMergedRegion(cellRange);
            cellRange = new CellRangeAddress(startRow, rowIndex - 1, 1, 1);
            sheet.addMergedRegion(cellRange);
        }

        // 自动调整列宽
        sheet.autoSizeColumn(0);
        sheet.autoSizeColumn(1);
        sheet.autoSizeColumn(2);
        sheet.autoSizeColumn(3);

        // 写入文件
        try (FileOutputStream fileOut = new FileOutputStream(excelName+"_fenxiap.xlsx")) {
            workbook.write(fileOut);
        }

        // 关闭工作簿
        workbook.close();

    }

    public static String convertToPercentString(BigDecimal value) {
        if (value == null) {
            return "";
        }

        // 将BigDecimal乘以100
        BigDecimal percentValue = value.multiply(BigDecimal.valueOf(100));

        // 使用DecimalFormat格式化结果，保留一位小数
        DecimalFormat decimalFormat = new DecimalFormat("0.0");
        String formattedValue = decimalFormat.format(percentValue);

        // 在末尾加上百分号
        return formattedValue + "%";
    }

    public static String maskIdCard(String idCard) {
        if (idCard == null || idCard.length() != 18) {
            return idCard;
        }

        StringBuilder maskedIdCard = new StringBuilder();
        maskedIdCard.append(idCard.substring(0, 6)); // 保留前6位
        maskedIdCard.append("************"); // 中间12位用*代替
        maskedIdCard.append(idCard.substring(14)); // 保留后4位

        return maskedIdCard.toString();
    }





}
